import {
	login,
	logout,
	getMenu
} from "@/api/auth";
import {
	getToken,
	setToken,
	removeToken,
	getUser,
	setUser,
	removeUser,
} from "@/utils/auth";
import {
	resetRouter
} from "@/router";
import store from "..";

const getDefaultState = () => {
	return {
		token: getToken(),
		user: getUser(),
	};
};

const state = getDefaultState();

const mutations = {
	RESET_STATE: (state) => {
		Object.assign(state, getDefaultState());
	},
	SET_TOKEN: (state, token) => {
		state.token = token;
	},
	SET_USER: (state, userInfo) => {
		state.user = userInfo;
	},
};

const actions = {
	// user login
	login({
		commit
	}, userInfo) {
		const {
			username,
			password
		} = userInfo;
		return new Promise((resolve, reject) => {
			login({
					username: username.trim(),
					password: password
				})
				.then((response) => {
					if (response.code === 200) {
						const {
							data
						} = response;
						// console.log(data)
						sessionStorage.setItem("userId", data.userId)
						sessionStorage.setItem("roleMenuList", JSON.stringify(data.roleMenuList))
						commit("SET_TOKEN", data.token);
						commit("SET_USER", data.token);
						setToken(data.token);
						setUser(data.token);
						resolve(data.token);
					} else {
						reject(response);
					}

				})
				.catch((error) => {

				});
		});
	},
	// get user menu
	getMenu({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			getMenu(store.getters.token)
				.then((response) => {
					const data = response;
					if (!data) {
						return reject("无法获取权限菜单，请重新登录");
					}
					resolve(data);
				})
				.catch((error) => {
					reject(error);
				});
		});
	},

	// user logout
	logout({
		commit,
		dispatch,
		state
	}) {
		return new Promise((resolve, reject) => {
			logout(state.token)
				.then(() => {
					removeToken(); // 删除token
					// 调用permission的action方法清空异步路由
					dispatch("permission/removeRoutes", {}, {
						root: true
					});
					resetRouter(); // 重置路由
					commit("RESET_STATE");
					resolve();
				})
				.catch((error) => {
					reject(error);
				});
		});
	},

	// 删除 Token
	resetToken({
		commit
	}) {
		return new Promise((resolve) => {
			removeToken(); // 必须删除cookie中的toke
			removeUser();
			commit("RESET_STATE");
			resolve();
		});
	},
};

export default {
	namespaced: true,
	state,
	mutations,
	actions,
};
